package com.example.rbacmanage.service.impl;

import com.example.rbacmanage.annotation.PermissionRange;
import com.example.rbacmanage.entity.Role;
import com.example.rbacmanage.entity.RoleDept;
import com.example.rbacmanage.entity.RoleMemu;
import com.example.rbacmanage.entity.UserRole;
import com.example.rbacmanage.exception.MyException;
import com.example.rbacmanage.mapper.RoleDeptMapper;
import com.example.rbacmanage.mapper.RoleMapper;
import com.example.rbacmanage.mapper.RoleMenuMapper;
import com.example.rbacmanage.mapper.UserRoleMapper;
import com.example.rbacmanage.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private RoleDeptMapper roleDeptMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public void save(Role role) {
        roleMapper.insert(role);
        if (!CollectionUtils.isEmpty(role.getMenuIds())){
            for (Long menuId:role.getMenuIds()){
                RoleMemu roleMemu = new RoleMemu();
                roleMemu.setRoleId(role.getId());
                roleMemu.setMenuId(menuId);
                roleMenuMapper.insert(roleMemu);
            }
        }
    }

    @Override
    public void remove(Long[] ids) {
        for(Long id:ids){
            roleMapper.del(id);
            //同时删除角色用户关系表、角色菜单表、角色部门表
            userRoleMapper.deleteByRoleId(id);
            roleMenuMapper.deleteByRoleId(id);
            roleDeptMapper.deleteByRoleId(id);

        }
    }

    @Override
    public void update(Role role) {
        roleMapper.update(role);
        RoleMemu roleMemu = new RoleMemu();
        roleMemu.setRoleId(role.getId());
        List<RoleMemu> roleMenus = roleMenuMapper.list(roleMemu);
        List<Long> oldMenuIds = roleMenus.stream().map(RoleMemu::getMenuId).collect(Collectors.toList());
        //判断原本的菜单在新菜单是否存在，不存在则删除
        for (RoleMemu rolemenu:roleMenus){
            boolean exist = false;
            if (role.getMenuIds().contains(rolemenu.getMenuId())){
                exist=true;
            }
            if (!exist){
                roleMenuMapper.del(rolemenu.getId());
            }
        }
        //判断新菜单在原本菜单是否存在，不存在，则新增
        for (Long menuId:role.getMenuIds()){
            boolean exist = false;
            if (oldMenuIds.contains(menuId)){
                exist=true;
            }
            if (!exist){
                RoleMemu roleMemu1 = new RoleMemu();
                roleMemu1.setRoleId(role.getId());
                roleMemu1.setMenuId(menuId);
                roleMenuMapper.insert(roleMemu1);
            }
        }
    }

    @PermissionRange(deptAlias = "d")
    @Override
    public List<Role> getAll(Role role) {
        return roleMapper.list(role);
    }

    @Override
    @PermissionRange(deptAlias = "d")
    public PageInfo<Role> getPage(Role role) {
        PageHelper.startPage(role.getPage(), role.getLimit());
        return new PageInfo<>(roleMapper.list(role));
    }

    @Override
    public Role getById(Long id) {
        Role role = roleMapper.queryOneById(id);
        if (role == null){
            return null;
        }
        RoleMemu roleMemu = new RoleMemu();
        roleMemu.setRoleId(id);
        List<RoleMemu> roleMenus = roleMenuMapper.list(roleMemu);
        List<Long> menuIds = roleMenus.stream().map(RoleMemu::getMenuId).filter(Objects::nonNull).collect(Collectors.toList());
        role.setMenuIds(menuIds);

        RoleDept roleDept = new RoleDept();
        roleDept.setRoleId(role.getId());
        List<RoleDept> roleDeptList = roleDeptMapper.list(roleDept);
        List<Long> deptIds = roleDeptList.stream().map(RoleDept::getDeptId).filter(Objects::nonNull).collect(Collectors.toList());
        role.setDeptIds(deptIds);
        return role;
    }

    @Override
    public Integer getCount(Role role) {
        return roleMapper.count(role);
    }

    @Override
    public void checkRepeat(Role role) throws MyException {

    }

    @Override
    public void assignPermission(Role role) {
        roleMapper.update(role);

        RoleDept roleDept = new RoleDept();
        roleDept.setRoleId(role.getId());
        List<RoleDept> roleDeptList = roleDeptMapper.list(roleDept);
        List<Long> deptIdsOld = roleDeptList.stream().map(RoleDept::getDeptId).collect(Collectors.toList());
        //判断原本的部门在新部门是否存在，不存在则删除
        for (RoleDept roledept:roleDeptList){
            boolean exist = false;
            if (role.getDeptIds().contains(roledept.getDeptId())){
                exist=true;
            }
            if (!exist){
                roleDeptMapper.del(roledept.getId());
            }
        }
        //判断新部门在原本部门是否存在，不存在，则新增
        for (Long deptId:role.getDeptIds()){
            boolean exist = false;
            if (deptIdsOld.contains(deptId)){
                exist=true;
            }
            if (!exist){
                RoleDept roledept = new RoleDept();
                roledept.setRoleId(role.getId());
                roledept.setDeptId(deptId);
                roleDeptMapper.insert(roledept);
            }
        }
    }

    @Override
    public void assignUsers(Role role) {
        if (!CollectionUtils.isEmpty(role.getUserIds())){
            for (Long userId:role.getUserIds()){
                UserRole userRole1 = new UserRole();
                userRole1.setRoleId(role.getId());
                userRole1.setUserId(userId);
                userRoleMapper.insert(userRole1);
            }
        }
    }

    @Override
    public void unAssignUsers(Long[] ids) {
       for (Long id:ids){
           userRoleMapper.del(id);
       }
    }
}
